package com.itheima.controller;

import com.itheima.pojo.Result;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

@Slf4j
@RestController
@Api(tags = "会话相关接口")
public class SessionController {
    /*Cookie*/
    /**
     * 设置Cookie  - 服务器端设置Cookie 并响应给浏览器
     */
    //设置请求方式和路径
    @GetMapping("/c1")
    @ApiOperation("设置Cookie")
    public Result cookie1(HttpServletResponse response) {
        //设置Cookie
        response.addCookie(new Cookie("login_cookie", "itheima"));

        //返回响应结果
        return Result.success();
    }


    /**
     * 获取Cookie  - 浏览器端接收到服务器端响应的Cookie 并获取自动保存
     */
    @GetMapping("/c2")
    @ApiOperation("获取Cookie")
    public Result cookie2(HttpServletRequest request) {
        //获取Cookie值 并封装为数组
        Cookie[] cookies = request.getCookies();

        //遍历数组
        for (Cookie cookie : cookies) {
            if (cookie.getName().equals("login_cookie")){
                System.out.println("login_cookie: "+ cookie.getValue());
            }
        }
        return Result.success();
    }

    /*Session*/

    /**
     * 设置Session
     * @param session
     * @return
     */
    @GetMapping("/s1")
    @ApiOperation("设置Session")
    public Result session1(HttpSession session){
        //记录日志
        log.info("session1: {}", session.hashCode());

        //设置Session值
        session.setAttribute("loginUser", "itheima");

        //返回响应结果
        return Result.success();
    }


    /**
     * 获取Session
     */
    @GetMapping("/s2")
    @ApiOperation("获取Session")
    public Result session2(HttpSession session){
        //记录日志
        log.info("session2: {}", session.hashCode());  //输出session2的hashcode值

        //获取loginUser session对象的Session值
        Object loginUser = session.getAttribute("loginUser");
        System.out.println(loginUser);

        //返回响应结果
        return Result.success();
    }
}
